package com.example.demo.controller.admincontroller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.ErrorCode;
import com.example.demo.common.Result;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * 用户管理控制器
 */
@RestController
@RequestMapping("/admin/user")
public class UserManageController {

    @Autowired
    private UserService userService;

    /**
     * 分页查询用户列表
     */
    @GetMapping("/list")
    public Result list(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String phone,
            @RequestParam(required = false) Integer status
    ) {
        Page<User> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        
        // 添加查询条件
        if (username != null && !username.isEmpty()) {
            wrapper.like(User::getUsername, username);
        }
        if (phone != null && !phone.isEmpty()) {
            wrapper.like(User::getPhone, phone);
        }
        if (status != null) {
            wrapper.eq(User::getStatus, status);
        }
        
        wrapper.orderByAsc(User::getId);
        
        Page<User> userPage = userService.page(page, wrapper);
        return Result.success(userPage);
    }

    /**
     * 获取用户详情
     */
    @GetMapping("/{id}")
    public Result getById(@PathVariable Long id) {
        User user = userService.getById(id);
        if (user == null) {
            return Result.error(ErrorCode.USER_NOT_EXIST);
        }
        return Result.success(user);
    }

    /**
     * 新增用户
     */
    @PostMapping
    public Result add(@RequestBody User user) {
        // 检查用户名是否已存在
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, user.getUsername());
        if (userService.count(wrapper) > 0) {
            return Result.error(ErrorCode.USERNAME_EXIST);
        }
        
        // 设置默认值
        user.setStatus(1); // 默认启用
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        
        if (userService.save(user)) {
            return Result.success();
        }
        return Result.error(ErrorCode.OPERATION_ERROR);
    }

    /**
     * 修改用户
     */
    @PutMapping
    public Result update(@RequestBody User user) {
        if (user.getId() == null) {
            return Result.error(ErrorCode.PARAMS_ERROR);
        }
        
        // 检查用户是否存在
        User existUser = userService.getById(user.getId());
        if (existUser == null) {
            return Result.error(ErrorCode.USER_NOT_EXIST);
        }
        
        // 如果修改了用户名，需要检查是否重复
        if (!existUser.getUsername().equals(user.getUsername())) {
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getUsername, user.getUsername());
            if (userService.count(wrapper) > 0) {
                return Result.error(ErrorCode.USERNAME_EXIST);
            }
        }
        
        user.setUpdateTime(LocalDateTime.now());
        if (userService.updateById(user)) {
            return Result.success();
        }
        return Result.error(ErrorCode.OPERATION_ERROR);
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Long id) {
        if (userService.removeById(id)) {
            return Result.success();
        }
        return Result.error(ErrorCode.OPERATION_ERROR);
    }

    /**
     * 修改用户状态
     */
    @PutMapping("/status")
    public Result updateStatus(@RequestParam Long id, @RequestParam Integer status) {
        if (status != 0 && status != 1) {
            return Result.error(ErrorCode.PARAMS_ERROR);
        }
        
        User user = new User();
        user.setId(id);
        user.setStatus(status);
        user.setUpdateTime(LocalDateTime.now());
        
        if (userService.updateById(user)) {
            return Result.success();
        }
        return Result.error(ErrorCode.OPERATION_ERROR);
    }
} 